package com.SouthernWall_404.AgeRight.Common.API.LockAPI;

import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class LockableBlocksRegistry {
    // 使用线程安全的集合，因为可能有多模组同时访问
    private static final Set<Block> LOCKABLE_BLOCKS = ConcurrentHashMap.newKeySet();
    private static final Set<TagKey<Block>> LOCKABLE_TAGS = ConcurrentHashMap.newKeySet();
    private static final Map<ResourceLocation, LockableCondition> CUSTOM_CONDITIONS = new ConcurrentHashMap<>();
    
    // 注册接口
    public interface LockableCondition {
        boolean isLockable(BlockState state);
    }
    
    // 注册单个方块
    public static void registerBlock(Block block) {
        if (block != null) {
            LOCKABLE_BLOCKS.add(block);
        }
    }
    
    // 注册标签
    public static void registerBlockTag(TagKey<Block> tagKey) {
        if (tagKey != null) {
            LOCKABLE_TAGS.add(tagKey);
        }
    }
    
    // 注册自定义条件
    public static void registerCondition(ResourceLocation id, LockableCondition condition) {
        if (id != null && condition != null) {
            CUSTOM_CONDITIONS.put(id, condition);
        }
    }
    
    // 检查方块是否可锁定
    public static boolean isLockable(BlockState blockState) {
        Block block = blockState.getBlock();
        
        // 检查直接注册的方块
        if (LOCKABLE_BLOCKS.contains(block)) {
            return true;
        }
        
        // 检查标签
        for (TagKey<Block> tag : LOCKABLE_TAGS) {
            if (blockState.is(tag)) {
                return true;
            }
        }
        
        // 检查自定义条件
        for (LockableCondition condition : CUSTOM_CONDITIONS.values()) {
            if (condition.isLockable(blockState)) {
                return true;
            }
        }
        
        return false;
    }
    
    // 获取所有已注册的可锁定方块（用于调试或显示）
    public static Collection<Block> getRegisteredBlocks() {
        return Collections.unmodifiableSet(LOCKABLE_BLOCKS);
    }
    
    // 获取所有已注册的标签（用于调试或显示）
    public static Collection<TagKey<Block>> getRegisteredTags() {
        return Collections.unmodifiableSet(LOCKABLE_TAGS);
    }
    
    // 获取所有已注册的自定义条件（用于调试或显示）
    public static Collection<ResourceLocation> getRegisteredConditions() {
        return Collections.unmodifiableSet(CUSTOM_CONDITIONS.keySet());
    }
    
    // 清除所有注册（主要用于测试）
    public static void clearRegistry() {
        LOCKABLE_BLOCKS.clear();
        LOCKABLE_TAGS.clear();
        CUSTOM_CONDITIONS.clear();
    }
}